package com.example.dqdq.lzyim_asm_tvapp.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.text.method.ScrollingMovementMethod;
import android.text.style.ClickableSpan;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.dqdq.lzyim_asm_tvapp.BootAdActivity;
import com.example.dqdq.lzyim_asm_tvapp.MainActivity;
import com.example.dqdq.lzyim_asm_tvapp.R;
import com.example.dqdq.lzyim_asm_tvapp.StartServerActivity;
import com.example.dqdq.lzyim_asm_tvapp.VedioActivity;
import com.example.dqdq.lzyim_asm_tvapp.adapter.AlwaysMarqueeTextView;
import com.example.dqdq.lzyim_asm_tvapp.adapter.GroudTextView;
import com.example.dqdq.lzyim_asm_tvapp.adapter.GroupScrollView;
import com.example.dqdq.lzyim_asm_tvapp.adapter.MarqueeText;
import com.example.dqdq.lzyim_asm_tvapp.adapter.URLImageGetter;
import com.example.dqdq.lzyim_asm_tvapp.api.API;
import com.example.dqdq.lzyim_asm_tvapp.https.HttpManger;
import com.example.dqdq.lzyim_asm_tvapp.utils.AutoScrollTextView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.x;

import java.io.IOException;
import java.net.URL;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayer;

//import net.sf.json.JSONObject;

/**
 * Created by DQDQ on 16/7/7.
 */
public class mBroadcastReceiver extends BroadcastReceiver {

    private View imgView;

    private WindowManager wm;
      private static WindowManager.LayoutParams params;
    private View subtitleView;
      private Integer textrecLen = 60;
     private Timer textTimer;
     private JSONObject obj;
    private Context mcontext;
    private  Integer jishu=0;
//    private
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.e("test", "isPush");
        Bundle bundle = intent.getExtras();
        String message = bundle.getString(JPushInterface.EXTRA_MESSAGE);//获取推送数据
        wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);

        try {
            if (message != null) {
                 obj = new JSONObject(message);
                Log.e("test msg",message);
                mcontext=context;
                Intent ootStartIntent = new Intent(context, VedioActivity.class);
                ootStartIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                ootStartIntent.putExtra("data",obj.toString());
                Log.e("test", obj.getString("content"));
                if (obj.getString("pushtype").equals("图片")) {

//                     ootStartIntent.putExtra("type","img");
//                    context.startActivity(ootStartIntent);


                    String[] imgs = obj.getString("content").split(",");//图片URL
                    String[] urls=obj.getString("forwardlink").split(",");//点击跳转到的网页
                    String[] pusshId=obj.getString("pushid").split(",");//每张图片的ID 用于记录点击量
                    showImg(context, imgs,urls,pusshId);


                }
                if (obj.getString("pushtype").equals("文字")) {

                    showText(context,obj.getString("content"),obj.getString("path"));
                    textTimer = new Timer();//定时自动关闭字幕
                    textTimer.schedule(textTimerTask, 1000, 1000);


                  }
                if (obj.getString("pushtype").equals("视频")) {
                    ootStartIntent.putExtra("type","vedio");

                     ootStartIntent.putExtra("vedioUrl",obj.getString("content"));
                    ootStartIntent.putExtra("loadImg",obj.getString("path"));
                    ootStartIntent.putExtra("vedioName",obj.getString("pushname"));
                    context.startActivity(ootStartIntent);


                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    /**
     * 显示图片
     * @param context
     * @param imgUrl
     * @param clickUrl
     * @param pusshId
     */
    private void showImg(final Context context, String[] imgUrl, final String[] clickUrl,final String[] pusshId) {
        LayoutInflater inflater = LayoutInflater.from(context);
        imgView = inflater.inflate(getImgView(imgUrl.length), null);

        Button button = (Button) imgView.findViewById(R.id.exitBtn);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                wm.removeView(imgView);

            }
        });


        ImageView imageView = (ImageView) imgView.findViewById(R.id.ad_code);
        Glide.with(context).load(API.ADCODE_IMG_URL).into(imageView);


        setImgBtn(context,imgView,imgUrl,clickUrl,pusshId);

        WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
        //窗口类型同系统弹出框
        lp.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
        //响应输入法
        //lp.flags = WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM;
        //透明层

//        lp.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
//                | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
//                | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
        lp.format = PixelFormat.TRANSPARENT;
        lp.width = 1000;
        lp.height = 700;
        lp.gravity = Gravity.CENTER_VERTICAL;
        wm.addView(imgView, lp);
    }
    /**
     * 根据图片数量设置图片按钮
     * @param context
     * @param view
     * @param imgs
     * @param urls
     * @param pusshId
     */
    private void setImgBtn(final Context context,View view,final String[] imgs,final  String[] urls,final  String[] pusshId)
    {

        Log.e("test", String.valueOf(urls.length));
        Log.e("test", String.valueOf(imgs.length));

        if (imgs.length>0)
        {
            ImageButton imageView = (ImageButton) view.findViewById(R.id.img1);
            Glide.with(context).load(API.SERVERC_URL + imgs[0]).into(imageView);
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    final Uri uri = Uri.parse(urls[0]);
                    final Intent it = new Intent(Intent.ACTION_VIEW, uri);
                    it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(it);
                    clickNumber(pusshId[0]);
                    wm.removeView(imgView);


                }
            });
        }

        if (imgs.length>1)
        {
            ImageButton imageView = (ImageButton) view.findViewById(R.id.img2);
            Glide.with(context).load(API.SERVERC_URL + imgs[1]).into(imageView);
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    clickNumber(pusshId[1]);
                    final Uri uri = Uri.parse(urls[1]);
                    final Intent it = new Intent(Intent.ACTION_VIEW, uri);
                    it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(it);
                    wm.removeView(imgView);

                }
            });
        }

        if (imgs.length>2)
        {
            ImageButton imageView = (ImageButton) view.findViewById(R.id.img3);
            Glide.with(context).load(API.SERVERC_URL + imgs[2]).into(imageView);
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    clickNumber(pusshId[2]);
                    final Uri uri = Uri.parse(urls[2]);
                    final Intent it = new Intent(Intent.ACTION_VIEW, uri);
                    it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(it);
                    wm.removeView(imgView);

                }
            });
        }

        if (imgs.length>3)
        {
            ImageButton imageView = (ImageButton) view.findViewById(R.id.img4);
            Glide.with(context).load(API.SERVERC_URL + imgs[3]).into(imageView);
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    clickNumber(pusshId[3]);
                    final Uri uri = Uri.parse(urls[3]);
                    final Intent it = new Intent(Intent.ACTION_VIEW, uri);
                    it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(it);
                    wm.removeView(imgView);

                }
            });
        }
        if (imgs.length>4)
        {
            ImageButton imageView = (ImageButton) view.findViewById(R.id.img5);
            Glide.with(context).load(API.SERVERC_URL + imgs[4]).into(imageView);
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    clickNumber(pusshId[4]);
                    final Uri uri = Uri.parse(urls[4]);
                    final Intent it = new Intent(Intent.ACTION_VIEW, uri);
                    it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(it);
                    wm.removeView(imgView);

                }
            });
        }

        if (imgs.length>5)
        {
            ImageButton imageView = (ImageButton) view.findViewById(R.id.img6);
            Glide.with(context).load(API.SERVERC_URL + imgs[5]).into(imageView);
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    clickNumber(pusshId[5]);
                    final Uri uri = Uri.parse(urls[5]);
                    final Intent it = new Intent(Intent.ACTION_VIEW, uri);
                    it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(it);
                    wm.removeView(imgView);

                }
            });
        }

        if (imgs.length>6)
        {
            ImageButton imageView = (ImageButton) view.findViewById(R.id.img7);
            Glide.with(context).load(API.SERVERC_URL + imgs[6]).into(imageView);
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    clickNumber(pusshId[6]);
                    final Uri uri = Uri.parse(urls[6]);
                    final Intent it = new Intent(Intent.ACTION_VIEW, uri);
                    it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(it);
                    wm.removeView(imgView);

                }
            });
        }

        if (imgs.length>7)
        {
            clickNumber(pusshId[7]);
            ImageButton imageView = (ImageButton) view.findViewById(R.id.img8);
            Glide.with(context).load(API.SERVERC_URL + imgs[7]).into(imageView);
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    final Uri uri = Uri.parse(urls[7]);
                    final Intent it = new Intent(Intent.ACTION_VIEW, uri);
                    it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(it);
                    wm.removeView(imgView);

                }
            });
        }
        if (imgs.length>8)
        {
            clickNumber(pusshId[8]);
            ImageButton imageView = (ImageButton) view.findViewById(R.id.img9);
            Glide.with(context).load(API.SERVERC_URL + imgs[8]).into(imageView);
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    final Uri uri = Uri.parse(urls[8]);
                    final Intent it = new Intent(Intent.ACTION_VIEW, uri);
                    it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(it);
                    wm.removeView(imgView);
                 }
            });
        }
    }

    /**
     * 根据图片数量获取不同的显示界面
     * @param length
     * @return
     */
    private int getImgView(int length)
    {
        int id=0;
        switch (length)
        {
            case 1:
            {
                id=R.layout.ad_img1_layout;
            }
            break;
            case 2:
            {
                id=R.layout.ad_img2_layout;
            }
            break;
            case 3:
            {
                id=R.layout.ad_img3_layout;
            }
            break;
            case 4:
            {
                id=R.layout.ad_img4_layout;
            }
            break;
            case 5:
            {
                id=R.layout.ad_img5_layout;
            }
            break;
            case 6:
            {
                id=R.layout.ad_img6_layout;
            }
            break;
            case 7:
            {
                id=R.layout.ad_img7_layout;
            }
            break;
            case 8:
            {
                id=R.layout.ad_img8_layout;
            }
            break;
            case 9:
            {
                id=R.layout.ad_img9_layout;
            }
            break;
        }

        return id;
    }



    Handler handler=new Handler()
    {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            try {
                wm.removeViewImmediate(subtitleView);
                showText(mcontext,obj.getString("content"),obj.getString("path"));
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    };
//    /**
//     * 显示滚动字幕
//     * @param context
//     * @param msg
//     */
//    private void showTexts(final Context context, String msg) {
//
//
//        LayoutInflater inflater = LayoutInflater.from(context);
//
//        subtitleView = inflater.inflate(R.layout.bottom, null);
//        GroudTextView editText1 = (GroudTextView) subtitleView.findViewById(R.id.tv_text);
//
//        String html = null;
//        try {
//            html = "<img src='" +  API.SERVERC_URL+obj.getString("path") + "'/>啊实打实的撒打算打算的";
//
////            Html.ImageGetter imgGetter = new Html.ImageGetter() {
////
////                @Override
////                public Drawable getDrawable(String source) {
////                    // TODO Auto-generated method stub
////
////                    int id = Integer.parseInt(source);
////                    if (id==3154)
////                        return result;
////                    Drawable d = mcontext.getResources().getDrawable(id);
////                    d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
////                    return d;                      }
////            };
////            CharSequence charSequence = Html.fromHtml(html, imgGetter, null);
////            editText1.setText(charSequence);
//            editText1.setMovementMethod(LinkMovementMethod.getInstance());//加这句才能让里面的超链接生效
//            URLImageGetter ReviewImgGetter = new URLImageGetter(mcontext, editText1);//实例化URLImageGetter类
//            editText1.setText(Html.fromHtml(html,ReviewImgGetter,null));
//            editText1.append(msg);
////                    obj.getString("content")
////                TextView editText1 = (TextView) subtitleView.findViewById(R.id.mSlod);
//
////            result.setBounds(0, 0, result.getIntrinsicWidth() / 4, result.getIntrinsicHeight() / 4);
////                editText1.setCompoundDrawables(result, null, null, null);
//            WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
//            //窗口类型同系统弹出框
//
//            lp.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
//            //响应输入法
//            //lp.flags = WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM;
//            //透明层
//
//            lp.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
//                    | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
//                    | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
//            lp.format = PixelFormat.TRANSPARENT;
//            lp.width = WindowManager.LayoutParams.MATCH_PARENT;
//            lp.height = WindowManager.LayoutParams.MATCH_PARENT;
//            lp.gravity = Gravity.CENTER_VERTICAL;
//
//            wm.addView(subtitleView, lp);
//
//            textrecLen = 60;
//            if (!obj.getString("frequency").equals("")&&!obj.getString("frequency").equals(""))
//            {
//                int frequency=Integer.parseInt(obj.getString("frequency"));
//                textrecLen=60*frequency;
//            }
//
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }
//
//
//
//
//    }
    /**
     * 定时关闭字幕
     */
    TimerTask textTimerTask = new TimerTask() {
        @Override
        public void run() {
            jishu++;



            Log.e("Test",String.valueOf(textrecLen)+" jishu:"+String.valueOf(jishu));
            if (textrecLen != 0) {
                textrecLen--;
            } else if (subtitleView != null) {
                wm.removeView(subtitleView);
                textTimer.cancel();
                Log.e("test","remove now");



                Intent intent1=new Intent(mcontext, StartServerActivity.class);
                intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                    wm=null;
                      params=null;
                    subtitleView=null;
                    textrecLen =null;
                    textTimer=null;
                    obj=null;
                    mcontext=null;

            }


        }
    };






    private void showText(Context context, String msg,String imgpath) throws JSONException {
        //        TextView msgTxv;
        LayoutInflater inflater = LayoutInflater.from(context);

        subtitleView = inflater.inflate(R.layout.bottom, null);

        if (!imgpath.equals(""))
            new DownloadImageTask().execute(API.SERVERC_URL+imgpath) ;



    }

    private class DownloadImageTask extends AsyncTask<String, Void, Drawable>
    {

        protected Drawable doInBackground(String... urls) {
            return loadImageFromNetwork(urls[0]);
        }

        protected void onPostExecute(final Drawable result) {
//                mImageView.setImageDrawable(result);

            if (result!=null)
            {

                MarqueeText textview = (MarqueeText) subtitleView.findViewById(R.id.text);
                /**             *
                 * 只有调用了该方法，TextView才能不依赖于ScrollView而实现滚动的效果。
                 * 要在XML中设置TextView的textcolor，否则，当TextView被触摸时，会灰掉。
                 */

//                textview.setMovementMethod(ScrollingMovementMethod.getInstance());
//                GroudTextView editText1 = (GroudTextView) subtitleView.findViewById(R.id.tv_text);
//                editText1.setSpeed(9);
                String html = null;
                try {
                    html = "<img src='" +  R.drawable.ic_back_white + "'/>";

            Html.ImageGetter imgGetter = new Html.ImageGetter() {

                @Override
                public Drawable getDrawable(String source) {
                    // TODO Auto-generated method stub

                    int id = Integer.parseInt(source);
                     result.setBounds(0, 0, 78, 52);
                    return result;

                }
            };
            CharSequence charSequence = Html.fromHtml(html, imgGetter, null);
                    textview.setText(charSequence);
                    textview.append(obj.getString("content"));
                    textview.startScroll();

//                    editText1.setCircleTimes(100);
//            editText1.setText(charSequence);
//                       editText1.append(obj.getString("content"));
                     WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
                    //窗口类型同系统弹出框

                    lp.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
                    //响应输入法
                    //lp.flags = WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM;
                    //透明层

                    double height = wm.getDefaultDisplay().getHeight()*0.057;
                    LinearLayout textheight= (LinearLayout) subtitleView.findViewById(R.id.texthei);
//                    textheight.hei
                    android.view.ViewGroup.LayoutParams ls=  textheight.getLayoutParams();
                    ls.height=(int) height;
                    Log.e("test window height",String.valueOf(height));
                     lp.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
                            | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                            | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
                    lp.format = PixelFormat.TRANSPARENT;
                    lp.width = WindowManager.LayoutParams.MATCH_PARENT;
                    lp.height = WindowManager.LayoutParams.MATCH_PARENT;
//                    lp.height = height;
                    lp.gravity = Gravity.CENTER_VERTICAL;

                    wm.addView(subtitleView, lp);

                    textrecLen = 60;
                    if (!obj.getString("frequency").equals("")&&!obj.getString("frequency").equals(""))
                    {
                        int frequency=Integer.parseInt(obj.getString("frequency"));
                        textrecLen=60*frequency;
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

        }
    }

    /**
     * 记录点击量
     * @param pushid
     */
    private void clickNumber(String pushid)
    {

        Log.e("Test","id="+pushid);
        if (pushid!=null&&pushid!="")
        {
            Log.e("Test","start");
            x.http().post(HttpManger.getParams(API.TV_CLICK, "id", pushid), new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    Log.e("Test","success");

                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    //  Toast.makeText(x.app(), ex.getMessage(), Toast.LENGTH_LONG).show();
                }

                @Override
                public void onCancelled(Callback.CancelledException cex) {
                    //   Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
                }

                @Override
                public void onFinished() {

                }
            });
        }
    }
    private Drawable loadImageFromNetwork(String imageUrl)
    {
        Drawable drawable = null;
        try {
            // 可以在这里通过文件名来判断，是否本地有此图片
            drawable = Drawable.createFromStream(
                    new URL(imageUrl).openStream(), "image.jpg");
        } catch (IOException e) {
            Log.d("test", e.getMessage());
        }
        if (drawable == null) {
            Log.d("test", "null drawable");
        } else {
            Log.d("test", "not null drawable");
        }

        return drawable ;
    }



}
